<?php

namespace App\Http\Controllers;

use App\Http\Requests\distributionRequest;
use App\Http\Requests\UserStoreRequest;
use App\Http\Requests\WorkRequest;
use App\Http\Resources\UserResource;
use App\Http\Resources\UserTypeResource;
use App\Models\Work;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Resources\Json\JsonResource
     */
    public function index(Request $request)
    {
        if (!$this->hasPermission([])) {
            return $this->respondPermission();
        }

        $data = User::with(['roles', 'permissions'])
            ->orderBy('id', 'desc')
            ->paginate($request->get('pageindex', 15));

        return UserResource::collection($data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  UserStoreRequest $request
     * @return UserResource
     */
    public function store(UserStoreRequest $request)
    {
        if (!$this->hasPermission('permission:manager')) {
            return $this->respondPermission();
        }

        $data             = $request->all();
        $data['password'] = bcrypt($data['password']);
        $user             = User::create($data);

        $this->syncModelPermission($user);
        $this->syncModelRole($user);

        return new UserResource($user);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \App\User                $user
     * @return UserResource
     */
    public function update(Request $request, User $user)
    {
        if (!$this->hasPermission('permission:manager')) {
            return $this->respondPermission();
        }

//        $this->syncModelPermission($user);
        $this->syncModelRole($user);
        $data = $request->all();

        if ($request->exists('password')) {
            $data['password'] = bcrypt($data['password']);
        } else {
            unset($data['password']);
        }

        $user->update($data);

        return new UserResource($user);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @throws (a)
     * @param  User $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        if (!$this->hasPermission('permission:manager')) {
            return $this->respondPermission();
        }
        $user->delete();
        return $this->responseSuccess(null, 204);
    }

    /**
     * Check Username Exists.
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function userExists(Request $request)
    {
        $field = $request->get('field', 'username');
        $name  = $request->get('value');
        $query = User::query();
        if ($id = $request->get('id', null)) {
            $query->where('id', '<>', $id);
        }
        $result = $query->where($field, $name)->exists();
        return $this->responseSuccess([
            'exists' => $result,
        ]);
    }

    public function typeUser(Request $request)
    {
        $type = $request->get('type');

        $type = "user:$type";

        $data = User::role($type)->get();
        return UserTypeResource::collection($data);
    }

    public function setWork(User $user, WorkRequest $request)
    {
        $id = $request->get('id');

        foreach ($id as $key => $value) {
            Work::query()->whereDate('date', $value)->where('user_id', $user->id)->delete();
            Work::create([
                'user_id'      => $user->id,
                'timetable_id' => $key,
                'date'         => $value
            ]);
        }
        return $this->responseSuccess();
    }

    public function workForDate($date)
    {
        $time = Carbon::parse($date);
        return User::whereHas('works', function ($query) use ($date, $time) {
            $query->whereTime('start_time', '<=', $time)
                ->whereTime('end_time', '>=', $time);
//            $query->whereDate('date', $date);
//            ->whereHas('timetable', function ($query) use ($time) {
//                $query->whereTime('start_time', '<=', $time)
//                    ->whereTime('end_time', '>=', $time);
//            });
        })->get();
    }

    public function workUser(Request $request)
    {
        $date = Carbon::parse($request->get('date', Carbon::now()->toDateString()));

        $dateString = $date->toDateString();
        $data       = Work::query()->whereDate('date', $dateString)
            ->whereHas('timetable', function ($query) use ($date) {
                $query->whereTime('start_time', '<=', $date)
                    ->whereTime('end_time', '>=', $date);
            })->with('users')
            ->get();

        $users = $this->workForDate($date);
        return UserResource::collection($users);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function switchStatus(Request $request)
    {
        $user   = $this->getUser();
        $status = $request->get('status', 0);
        $user->update([
            'status' => $status,
        ]);
        return $this->responseSuccess(null, 204);
    }

}
